/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package util;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.StringWriter;
/**
 *
 * @author wudihua
 */
public class FormatUtil {
    
    public static void main(String[] args) {
        String json = "{\"resourceType\":\"OperationOutcome\",\"id\":\"4028f8a4647cd5c801647cd5ff070002\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2018-07-09T10:19:16.616+08:00\"},\"text\":{\"status\":\"generated\",\"div\":\"<div xmlns=\\\"http://www.w3.org/1999/xhtml\\\"><h1>Operation Outcome</h1><table border=\\\"0\\\"><tr><td style=\\\"font-weight: bold;\\\">INFORMATION</td><td>[]</td><td><pre>Successfully created resource \\\"Bundle/4028f8a4647cd5c801647cd5ff070002/_history/1\\\" in 4ms</pre></td><td style=\\\"font-weight: bold;\\\">INFORMATION</td><td>[]</td><td><pre>No issues detected during validation</pre></td></tr></table></div>\"},\"issue\":[{\"severity\":\"information\",\"code\":\"informational\",\"diagnostics\":\"Successfully created resource \\\"Bundle/4028f8a4647cd5c801647cd5ff070002/_history/1\\\" in 4ms\"},{\"severity\":\"information\",\"code\":\"informational\",\"diagnostics\":\"No issues detected during validation\"}]}";
        System.out.println(formatJson(json));
    }
    
     
     public static String formatJson(String json) {
        String formatJson = "";
        ObjectMapper mapper = new ObjectMapper();
        try {
            Object obj = mapper.readValue(json, Object.class);
            formatJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return formatJson;
    }
    
   
    public static String formatXml(String str){
        XMLWriter xmlwriter = null;
        try{
            Document document;
            document = DocumentHelper.parseText(str);
            OutputFormat format = OutputFormat.createPrettyPrint();
            StringWriter writer = new StringWriter();
            xmlwriter = new XMLWriter(writer,format);
            xmlwriter.write(document);
            return writer.toString();
        }catch(Exception e){
            e.printStackTrace();
            return str;
        }finally{
            if(xmlwriter != null){
                try{
                    xmlwriter.close();
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
        }
    }
}
